package cn.nb12.xbox.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 汇率工具
 * @author yh
 *
 */
public class ExchangeRateUtil {
	
	
	/**
	 * 接口链接
	 */
	public final static String url="http://qq.ip138.com/hl.asp?from=<from>&to=<to>&q=1";
	
	/**
	 * 获得费率
	 * @param from 原币种
	 * @param to 目标币种
	 * @return
	 */
	public static String getExchangeRate(String from,String to) {
		String response;
		try {
			Map<String,String> headers=new HashMap<>();
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0");
			response = RequestUtil.sendPost(url.replaceAll("<from>", from).replaceAll("<to>", to),"" ,headers,"GB2312");
			Document doc = Jsoup.parse(response);
			Elements select = doc.select("table.rate");
			if(select!=null && select.size()==1) {
				Elements select2 = select.select("tr td");
				if(select2!=null && select2.size()==6) {
					Element element = select2.get(4);
					return element.html();
				}
			}
		} catch (IOException e) {
			throw new RuntimeException("更新汇率时发生异常",e);
		}
		return "1";
	}
	public static void main(String[] args) {
		String cny = getExchangeRate("HKD", "CNY");
		System.out.println(cny);
	}
}
